// app.js
App({
  globalData: {
    isLoggedIn: false,
    userInfo: null,
    currentExamResult: null,
    baseUrl: 'http://localhost:8080/api'  // 添加正确格式的API基础URL
  },

  onLaunch() {
    console.log('App onLaunch');
    
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 设置状态栏高度为CSS变量
    wx.setStorageSync('statusBarHeight', systemInfo.statusBarHeight);
    
    // 在小程序环境中，可以使用以下方法设置CSS变量
    if (wx.canIUse('nextTick')) {
      wx.nextTick(() => {
        let pages = getCurrentPages();
        if (pages.length) {
          pages[0].setData({
            statusBarHeightCSS: systemInfo.statusBarHeight + 'px'
          });
        }
      });
    }

    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 检查登录状态
    this.checkLoginStatus();
    
    console.log('App onLaunch完成, globalData:', this.globalData);
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    console.log('App checkLoginStatus');
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');
    
    console.log('App 本地存储:', { token, userInfo });
    
    if (token && userInfo) {
      this.globalData.isLoggedIn = true;
      this.globalData.userInfo = userInfo;
    } else {
      this.globalData.isLoggedIn = false;
      this.globalData.userInfo = null;
      // 清除可能存在的残留数据
      wx.removeStorageSync('token');
      wx.removeStorageSync('userInfo');
    }
    
    console.log('App globalData:', this.globalData);
  },

  /**
   * 更新登录状态
   */
  updateLoginStatus(isLoggedIn, userInfo = null) {
    console.log('App updateLoginStatus:', { isLoggedIn, userInfo });
    
    this.globalData.isLoggedIn = isLoggedIn;
    this.globalData.userInfo = userInfo;
    
    if (isLoggedIn && userInfo) {
      // 确保存储了登录信息
      const token = wx.getStorageSync('token');
      if (!token) {
        console.warn('Token未存储');
      }
    } else {
      // 清除存储的登录信息
      wx.removeStorageSync('token');
      wx.removeStorageSync('userInfo');
    }
    
    console.log('App globalData更新后:', this.globalData);
  }
})
